package com.lysj.bhp.api.controller;

import com.lysj.bhp.api.base.ApiContent;
import com.lysj.bhp.borrowing.domain.BorrowingInstallment;
import com.lysj.bhp.borrowing.domain.BorrowingRecord;
import com.lysj.bhp.borrowing.domain.ServiceCharge;
import com.lysj.bhp.borrowing.vo.BorrowingRecordVo;
import com.lysj.bhp.util.random.FormatUtil;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import com.lysj.bhp.wallet.domain.BhpcWallet;
import com.lysj.bhp.wallet.domain.BitCoinWallet;
import com.lysj.bhp.wallet.domain.EthereumWallet;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.beans.Beans;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v2/user")
@Api(value = "ApiBorrowingController", tags = "去还款界面模块接口")
public class ApiBorrowingManageController extends ApiContent {


    /**
     * @author drj
     * @date 2018/8/24 9:08
     * @Description:去还款界面,显示当前还款信息
     * 2018-09-04 11点01分 zwj修改已还未还金额显示部分
     */
    @GetMapping("/borrowing_manage")
    public Resp borrowingRecordInfo(Long borrowingRecordId) {
        Map<String, Object> map = new HashMap<>();
        if (ParamUtil.isBlack(borrowingRecordId)) {
            return new Resp(Resp.PARAM_ERROR, "未知错误,请联系管理员");
        }
        BorrowingRecord borrowingRecord = borrowingContent.borrowingRecordRepository.findOne(borrowingRecordId);
        if (null == borrowingRecord) {
            return new Resp(Resp.PARAM_ERROR, "未知错误,请联系管理员");
        }
        BorrowingRecordVo borrowingRecordVo = new BorrowingRecordVo();
        BeanUtils.copyProperties(borrowingRecord, borrowingRecordVo);
        if(1==borrowingRecord.getRefundWay()){
            borrowingRecordVo.setProgressInfo("0/1");
        }else{
            borrowingRecordVo.setProgressInfo(borrowingRecordVo.getProgress() + "/" + borrowingRecordVo.getDeadline());
        }
        //获取借款记录当前期的还款明细
        BorrowingInstallment borrowingInstallment = borrowingContent.borrowingInstallmentRepository.findByUserIdAndBorrowingRecordIdAndNper(currentUser().getUserId(), borrowingRecord.getBorrowingRecordId(), borrowingRecord.getProgress() + 1);
        //本期应还(本金+利息)
        borrowingRecordVo.setCurrentDebtMoney(borrowingInstallment.getReturnMoney().add(borrowingInstallment.getReturnDividend()));
        //还款日期
        borrowingRecordVo.setReturnMoneyDate(borrowingInstallment.getEndRepaymentDate());
        //违约金
        borrowingRecordVo.setDefaultMoney(borrowingInstallment.getDefaultMoney());
        List<BorrowingInstallment> borrowingInstallments = borrowingContent.borrowingInstallmentRepository.findByBorrowingRecordIdOrderByNperAsc(borrowingRecord.getBorrowingRecordId());
        BigDecimal totolOffPaidDebtMoney = new BigDecimal(BigInteger.ZERO);
        BigDecimal totolNoPaidDebtMoney = new BigDecimal(BigInteger.ZERO);
        //逾期
        Date nowDate = FormatUtil.getDayEndDay(new Date());
        if(nowDate.equals(borrowingInstallment.getEndRepaymentDate())){
            borrowingRecordVo.setDefaultStatus(3);
        }
        else{
            borrowingRecordVo.setDefaultStatus(borrowingInstallment.getDefaultState());
        }
        //应还金额
        BigDecimal returnMoney = borrowingInstallment.getReturnMoney().add(borrowingInstallment.getReturnDividend().add(borrowingInstallment.getDefaultMoney()));
        for (int i = 0; i < borrowingInstallments.size(); i++) {
            borrowingInstallment = borrowingInstallments.get(i);
            //未还
            if(ParamUtil.isBlack(borrowingInstallment.getActualRepaymentDate())){
                totolNoPaidDebtMoney = totolNoPaidDebtMoney.add(borrowingInstallment.getReturnMoney().add(borrowingInstallment.getReturnDividend().add(borrowingInstallment.getDefaultMoney())));
            }
            //已还
            else{
                totolOffPaidDebtMoney = totolNoPaidDebtMoney.add(borrowingInstallment.getReturnMoney().add(borrowingInstallment.getReturnDividend().add(borrowingInstallment.getDefaultMoney())));
            }
        }
        borrowingRecordVo.setCurrentDebtMoney(borrowingRecordVo.getCurrentDebtMoney().setScale(6,BigDecimal.ROUND_HALF_UP));
        //已还金额
        borrowingRecordVo.setOffDebtMoney(totolOffPaidDebtMoney.setScale(6,BigDecimal.ROUND_HALF_UP));
        //未还金额
        borrowingRecordVo.setNoDebtMoney(totolNoPaidDebtMoney.setScale(6,BigDecimal.ROUND_HALF_UP));
        //借款金额转CNY
        borrowingRecordVo.setBorrowingMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingRecordVo.getBorrowingType(),borrowingRecordVo.getBorrowingMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
        //抵押金额转CNY
        borrowingRecordVo.setMortgageMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingRecordVo.getMortgageType(),borrowingRecordVo.getMortgageMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
        //本期应还转CNY
        borrowingRecordVo.setCurrentDebtMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingRecordVo.getBorrowingType(),borrowingRecordVo.getCurrentDebtMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
        //已还金额转CNY
        borrowingRecordVo.setOffDebtMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingRecordVo.getBorrowingType(),borrowingRecordVo.getOffDebtMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
        //未还金额转CNY
        borrowingRecordVo.setNoDebtMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingRecordVo.getBorrowingType(),borrowingRecordVo.getNoDebtMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
        //违约金转CNY
        borrowingRecordVo.setDefaultMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingRecordVo.getBorrowingType(),borrowingRecordVo.getDefaultMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
       //显示用户对应钱包的可用余额
        map.put("borrowingRecordVo",borrowingRecordVo);
        //显示对应钱包的可用余额
        map.putAll(map(borrowingRecord.getUserId(),borrowingRecord.getBorrowingType(),borrowingRecordVo.getCurrentDebtMoney()));
        map.putAll( map("returnMoney",returnMoney.setScale(6,BigDecimal.ROUND_HALF_UP), borrowingRecord.getBorrowingType()));
        return new Resp(map);
    }
    /**
     * @author drj
     * @date 2018/8/24 9:44
     * @Description:显示用户提前还款金额
     */
    @GetMapping("/show_advance_money")
    public Resp showAdvanceMoney(Long borrowingRecordId) throws Exception {
        Map<String, Object> map  ;
        if (ParamUtil.isBlack(borrowingRecordId)) {
            return new Resp(Resp.PARAM_ERROR, "请联系管理员");
        }
        BorrowingRecord borrowingRecord = borrowingContent.borrowingRecordRepository.findOne(borrowingRecordId);
        if (ParamUtil.isBlack(borrowingRecord)) {
            return new Resp(Resp.PARAM_ERROR, "请联系管理员");
        }
        BigDecimal returnMoney = new BigDecimal(BigInteger.ZERO);
        BigDecimal currentReturnMoney = new BigDecimal(BigInteger.ZERO);
        //违约金
        BigDecimal penalSumMoney = new BigDecimal(BigInteger.ZERO);
        //手续费
        ServiceCharge serviceCharge = borrowingContent.serviceChargeRepository.findOne(1L);
        BigDecimal serviceRate = serviceCharge.getServiceRate().divide(new BigDecimal(100));
        //判定该还款记录利率类型 1:按天还款,2：按月还款
        BorrowingInstallment borrowingInstallment = borrowingContent.borrowingInstallmentRepository.findByUserIdAndBorrowingRecordIdAndNper(borrowingRecord.getUserId(), borrowingRecord.getBorrowingRecordId(), borrowingRecord.getProgress() + 1);
        long currentTime = System.currentTimeMillis();
        //提前还款月模式下违约金开关
        Boolean monthDefaultMoneySwitch = true;
        if(borrowingRecord.getRefundWay() == 1){
            System.out.println(borrowingRecord);
            //到期还本付息 按天
            if(borrowingRecord.getRateType() == 1){
                if(borrowingInstallment.getBeginRepaymentDate().getTime() > new Date(currentTime).getTime()){
                    returnMoney = borrowingInstallment.getReturnMoney().add(borrowingInstallment.getReturnDividend().multiply(serviceRate)).setScale(18,BigDecimal.ROUND_HALF_UP);
                }
                else if(borrowingInstallment.getBlacklistId() != 0){
                    returnMoney = returnMoney.add(borrowingInstallment.getReturnMoney().add(borrowingInstallment.getReturnDividend()).add(borrowingInstallment.getDefaultMoney()));
                }
                else{
                    returnMoney = borrowingContent.returnMoneyService.prepayment(borrowingInstallment.getBeginRepaymentDate(),FormatUtil.getDayStartDay(borrowingInstallment.getEndRepaymentDate()),new Date(currentTime),borrowingInstallment.getReturnMoney(),borrowingInstallment.getReturnDividend(),serviceRate).get("currentReturnMoney");
                }
            }
            else{
                //这边先切3个时间段出来。用if判断时间断。 3个判断添加
                //每月应该还的利息
                if(borrowingInstallment.getBlacklistId() != 0){
                    returnMoney = returnMoney.add(borrowingInstallment.getReturnMoney().add(borrowingInstallment.getReturnDividend()).add(borrowingInstallment.getDefaultMoney()));
                }
                else{
                    BigDecimal returnDividend = borrowingInstallment.getReturnDividend().divide(new BigDecimal(borrowingRecord.getDeadline()),18,BigDecimal.ROUND_HALF_UP);
                    penalSumMoney = borrowingContent.returnMoneyService.duePaymentsInterest(borrowingRecord,borrowingInstallment,currentTime,returnDividend,serviceRate).get("sumMoney");
                    returnMoney = returnMoney.add(borrowingInstallment.getReturnMoney()).add(penalSumMoney);
                }
            }
        }
        else{
            for (int i = borrowingRecord.getProgress() + 1; i <= borrowingRecord.getDeadline(); i++) {
                borrowingInstallment = borrowingContent.borrowingInstallmentRepository.findByUserIdAndBorrowingRecordIdAndNper(currentUser().getUserId(), borrowingRecord.getBorrowingRecordId(), i);
                if(borrowingInstallment.getBlacklistId() != 0 ){
                    returnMoney = returnMoney.add(borrowingInstallment.getReturnMoney().add(borrowingInstallment.getReturnDividend()).add(borrowingInstallment.getDefaultMoney()));
                }
                else if(FormatUtil.isBetweenTime(new Date(currentTime), borrowingInstallment.getBeginRepaymentDate(), borrowingInstallment.getEndRepaymentDate())){
                    //提前为日还款 本日照常算利息
                    if(borrowingRecord.getRateType() == 1){
                        returnMoney = returnMoney.add(borrowingInstallment.getReturnMoney().add(borrowingInstallment.getReturnDividend()));
                    }
                    //提前为月还款 调用方法计算当月提前状态下金额
                    else{
                        returnMoney = returnMoney.add(borrowingContent.returnMoneyService.advancedCurrent(borrowingInstallment,serviceRate).get("currentReturnMoney"));
                    }
                }
                else{
                    //如果为天，则是后面剩余的所有违约金相加
                    if(borrowingRecord.getRateType() == 1){
                        penalSumMoney = borrowingInstallment.getReturnDividend().multiply(serviceRate);
                    }
                    //如果为月，只取一个月的违约金
                    else{
                        if (monthDefaultMoneySwitch) {
                            penalSumMoney = borrowingInstallment.getReturnDividend().multiply(serviceRate);
                            monthDefaultMoneySwitch = false;
                        } else {
                            penalSumMoney = new BigDecimal(BigInteger.ZERO);
                        }
                    }
                    returnMoney = returnMoney.add(borrowingInstallment.getReturnMoney().add(penalSumMoney));
                    System.out.println(returnMoney);
                }
            }
            returnMoney = returnMoney.setScale(6,BigDecimal.ROUND_HALF_UP);
        }
        map = map("returnMoney",returnMoney.setScale(6,BigDecimal.ROUND_HALF_UP), borrowingRecord.getBorrowingType());
        BigDecimal availBalance = availBalance(borrowingRecord.getUserId(),borrowingRecord.getBorrowingType());
        Integer status = 1;
        if(availBalance.compareTo(returnMoney) == -1){
            status = -1;
        }
        map.put("availBalanceStatus",status);
        return new Resp(map);
    }
    /**
     * @author drj
     * @date 2018/8/24 9:44
     * @Description:还款
     */
    @PostMapping("/refund_money")
    @ApiOperation(value = "还款接口", notes = "借款ID：Long borrowingRecordId，还款方式：Integer operate 1.当期 2.提前全部，付款密码：String tradePassword")
    public Resp refundMoney(Long borrowingRecordId, Integer operate, String tradePassword) throws Exception {
        Resp resp = borrowingContent.returnMoneyService.returnMoney(borrowingRecordId,operate,tradePassword);
        return resp;
    }
    /**
     * @author drj
     * @date 2018/8/24 9:08
     * @Description:计算违约金和抵押资产的方法
     */
    public Map<String, Object> map(String name, BigDecimal money, Integer type) {
        Map<String, Object> map = new HashMap<>();
        BigDecimal exchangeRate = new BigDecimal("1");
        String walletName = "";
        switch (type) {
            case 10:
                exchangeRate = exchangeRateService.bitcoinToCnyRate();
                walletName = "BTC";
                break;
            case 20:
                exchangeRate = exchangeRateService.ethToCnyRate();
                walletName = "ETH";
                break;
            case 100:
                exchangeRate = exchangeRateService.bhpcToCnyRate();
                walletName = "BHPC";
                break;
        }
        map.put(name, money + walletName);
        map.put(name + "CNY", money.multiply(exchangeRate).setScale(2, BigDecimal.ROUND_HALF_UP));
        return map;
    }
    /**
     * @author zwj
     * @date 2018-08-30 16:03
     * @@Description: 计算本钱包账户余额
     */
    public String accountBalance(Integer type){
        String walletName = "";
        BigDecimal exchangeRate = new BigDecimal(BigInteger.ZERO);
        switch (type) {
            case 10:
                exchangeRate = exchangeRateService.bitcoinToCnyRate();
                walletName = "BTC";
                break;
            case 20:
                exchangeRate = exchangeRateService.ethToCnyRate();
                walletName = "ETH";
                break;
            case 100:
                exchangeRate = exchangeRateService.bhpcToCnyRate();
                walletName = "BHPC";
                break;
        }
        return  exchangeRate+walletName;
    }

    public BigDecimal availBalance(Long userId,Integer type){
        BigDecimal availBalance = new BigDecimal(BigInteger.ZERO);
        switch (type) {
            case 10:
                availBalance = bitcoinWalletRepository.findByUserId(userId).getAvailBalance();
                break;
            case 20:
                availBalance = ethereumWalletRepository.findByUserId(userId).getAvailBalance();
                break;
            case 100:
                availBalance = bhpcWalletRepository.findByUserId(userId).getAvailBalance();
                break;
        }
        return availBalance;
    }
    public Map<String,Object>  map(Long userId, Integer type ,BigDecimal currentDebtMoney ) {
        Map<String,Object> map=new HashMap<>();
        BigDecimal availBalance = new BigDecimal(BigInteger.ZERO);
        BigDecimal availBalanceCny = new BigDecimal(BigInteger.ZERO);
        Integer status = 1;
        map.put("availBalance",availBalance);
        map.put("availBalanceCny",availBalanceCny);

        switch (type) {
            case 10:
               BitCoinWallet bitCoinWallet=bitcoinWalletRepository.findByUserId(userId);
               if(null!=bitCoinWallet){
                   map.put("availBalance",bitCoinWallet.getAvailBalance().setScale(6,BigDecimal.ROUND_HALF_UP));
                   map.put("availBalanceCny",bitCoinWallet.getAvailBalance().multiply(exchangeRateService.bitcoinToCnyRate().setScale(2,BigDecimal.ROUND_HALF_UP)));
                   if(bitCoinWallet.getAvailBalance().compareTo(currentDebtMoney) == -1){
                       status = -1;
                   }
               }
                break;
            case 20:
                EthereumWallet ethereumWallet=ethereumWalletRepository.findByUserId(userId);
                if(null!=ethereumWallet){
                    map.put("availBalance",ethereumWallet.getAvailBalance().setScale(6,BigDecimal.ROUND_HALF_UP));
                    map.put("availBalanceCny",ethereumWallet.getAvailBalance().multiply(exchangeRateService.ethToCnyRate().setScale(2,BigDecimal.ROUND_HALF_UP)));
                    if(ethereumWallet.getAvailBalance().compareTo(currentDebtMoney) == -1){
                        status = -1;
                    }
                }
                break;
            case 100:
                BhpcWallet bhpcWallet=bhpcWalletRepository.findByUserId(userId);
                if(null!=bhpcWallet){
                    map.put("availBalance",bhpcWallet.getAvailBalance().setScale(6,BigDecimal.ROUND_HALF_UP));
                    map.put("availBalanceCny",bhpcWallet.getAvailBalance().multiply(exchangeRateService.bhpcToCnyRate().setScale(2,BigDecimal.ROUND_HALF_UP)));
                    if(bhpcWallet.getAvailBalance().compareTo(currentDebtMoney) == -1){
                        status = -1;
                    }
                }
                break;
        }
        map.put("availBalanceStatus",status);
        return map;
    }


}
